package bibbletex.helpers;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * DBConnector is a class implementing the singleton pattern to provide an 
 * unique connection to the database shared for all the application
 * 
 * WARNING: The database must contain a valid shema
 * 
 * @author Diego Barrios Romero
 */
public class DBConnector {
	private static DBConnector INSTANCE = new DBConnector();

	Connection connection;

	public static Connection getConnection() {
		return INSTANCE.connection;
	}

	private DBConnector() {
		try {
			// load the sqlite-JDBC driver using the current class loader
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			System.err.println("Class not found exception");
		}
		connection = null;
		try {
			// create a database connection
			connection = DriverManager.getConnection("jdbc:sqlite:data.db");
			if (connection == null)
				throw new SQLException("DBConnector: The connection to the database could not be stablished!");
			// WARNING: The database must contain a valid schema
		} catch (SQLException e) {
			// if the error message is "out of memory",
			// it probably means no database file is found
			System.err.println(e.getMessage());
		}
	}
}
